package com.pm.main.common;

import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;
import java.util.function.Function;

/**
 * @author admin
 * @date 2020/11/2
 **/
public interface PageRepository {


     ReactiveMongoTemplate getReactiveMongoTemplate();
     Function<PageReq, Pageable> getPageMapper();


    default  <T, R> Mono<PageRsp<R>> page(Query query, PageReq pageReq, Class<T> clazz, Function<T, R> convert) {
        return page(query, getPageMapper().apply(pageReq), clazz, convert);
    }

    default  <T, R> Mono<PageRsp<R>> page(Query query, Pageable pageable, Class<T> clazz, Function<T, R> convert) {
        final Long count = getReactiveMongoTemplate().count(query, clazz).blockOptional().orElse(0L);
        return getReactiveMongoTemplate().find(query, clazz)
                .map(convert)
                .collectList().map(a->PageRsp.of(count, pageable.getPageSize(), a));
    }
}
